package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdUserDTO DTO) {
        String name = DTO.getName();
        String password = DTO.getPassword();
        if (StringUtils.isBlank(name)||StringUtils.isBlank(password)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");

        }
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (adUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");

        }
        String s = DigestUtils.md5DigestAsHex((password + adUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        if (!s.equalsIgnoreCase(adUser.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码输入错误");

        }
        if (adUser.getStatus().intValue()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常");
        }
        adUser.setLoginTime(new Date());
        this.updateById(adUser);
        AdUserVO vo = new AdUserVO();

        BeanUtils.copyProperties(adUser,vo);
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        HashMap result = new HashMap<>();
        result.put("token",token);
        result.put("user",vo);
        System.out.println("登录成功");
        return ResponseResult.okResult(result);
    }
}
